using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 流血Buff - 持续造成物理伤害
/// </summary>
public class BleedBuff : BuffBase
{
    private float m_TickInterval = 1.0f; // 每秒造成一次伤���
    private float m_LastTickTime;
    private long m_DamagePerTick;
    private float m_DamageMultiplier = 1.0f; // 伤害倍率

    public BleedBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is BleedData bleedData)
        {
            m_DamagePerTick = bleedData.DamagePerTick;
            m_TickInterval = bleedData.TickInterval;
            m_DamageMultiplier = bleedData.DamageMultiplier;
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        m_LastTickTime = 0f;
        
        // 播放流血特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        Logger.Log($"{Target.name} 开始流血，每秒造成 {m_DamagePerTick} 点物理伤���");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        
        // 检查是否到了造成伤害的时���
        if (Time.time - m_LastTickTime >= m_TickInterval)
        {
            ApplyBleedDamage();
            m_LastTickTime = Time.time;
        }
    }

    private void ApplyBleedDamage()
    {
        if (Target != null && !Target.HealthComponent.IsDead)
        {
            // 计算实际伤害（考虑倍率���
            long actualDamage = (long)(m_DamagePerTick * m_DamageMultiplier);
            
            // 造成物理伤害
            Target.HealthComponent.TakeDamage(actualDamage);
            
            Logger.Log($"{Target.name} 受到流血伤害: {actualDamage}");
            
            // 触发伤害事件
            var args = ReferencePool.Acquire<EntityTakeDamageEventArgs>();
            args.Entity = Target;
            args.Damage = actualDamage;
            args.Attacker = Caster;
            EventHelper.Fire(this, args);
        }
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log($"{Target.name} 流血效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("Bleed"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return true; // 流血效果可以叠加，刷新持续时���
    }
}
